package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	fmt.Println("=== 聊天系统测试 ===")

	// 测试发送消息
	fmt.Println("\n1. 测试发送消息...")
	sendMessage()

	// 等待一下让消息处理
	time.Sleep(2 * time.Second)

	// 测试获取聊天历史
	fmt.Println("\n2. 测试获取聊天历史...")
	getHistory()

	// 测试时间范围查询
	fmt.Println("\n3. 测试时间范围查询...")
	getHistoryByTimeRange()

	// 测试未读消息数量
	fmt.Println("\n4. 测试未读消息数量...")
	getUnreadCount()

	fmt.Println("\n测试完成!")
}

func sendMessage() {
	url := "http://localhost:8000/v1/chat/send"
	message := map[string]interface{}{
		"sender_id":   "user1",
		"receiver_id": "user2",
		"message": map[string]interface{}{
			"type":    1,
			"content": "Hello from test program!",
		},
		"timestamp": time.Now().Unix(),
	}

	jsonData, _ := json.Marshal(message)
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("❌ 发送消息失败: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("✅ 发送消息响应: %s\n", string(body))
}

func getHistory() {
	url := "http://localhost:8000/v1/chat/history?user_id_1=user1&user_id_2=user2&page=1&page_size=10"
	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("❌ 获取历史失败: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("✅ 历史记录响应: %s\n", string(body))
}

func getHistoryByTimeRange() {
	startTime := time.Now().Add(-1 * time.Hour).Unix()
	endTime := time.Now().Add(1 * time.Hour).Unix()
	url := fmt.Sprintf("http://localhost:8000/v1/chat/history/range?user_id_1=user1&user_id_2=user2&start_time=%d&end_time=%d&limit=50", startTime, endTime)

	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("❌ 时间范围查询失败: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("✅ 时间范围查询响应: %s\n", string(body))
}

func getUnreadCount() {
	url := "http://localhost:8000/v1/chat/unread/count?user_id=user2"
	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("❌ 获取未读数量失败: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("✅ 未读数量响应: %s\n", string(body))
}
